#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>

/*
 * client和serve都创建一个线程进行获取输入和发送输入内容，原来主线程会将接收到的内容打印出来，
 * 当输入内容或则接收内容为“bye”时将退出程序运行。
 */ 

int getchar_input_str(char * input_buff);

int g_flag_exit = 0;
char input_str[100], read_buff[100];
int serv_sock_fd;
int clnt_sock_fd;

void * TCP_send(void *arg)
{
    int input_count = 0;
    
    while(1) {
        printf("self:");
        input_count = getchar_input_str(input_str);
        send(clnt_sock_fd, input_str, input_count + 1, 0);
        
        //printf("serve:[%d] %s\n", input_count, input_str);
        if (input_str[0] == 'b' && input_str[1] == 'y' && input_str[2] == 'e') {
            g_flag_exit = 1;
            
            return NULL;
        }
    }    
}

int main()
{
    //创建套接字
    serv_sock_fd = socket(AF_INET, SOCK_STREAM, 0);

    //向服务器（特定的IP和端口）发起请求
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));  //每个字节都用0填充
    serv_addr.sin_family = AF_INET;  //使用IPv4地址
    serv_addr.sin_addr.s_addr = inet_addr("172.16.194.184");  //具体的IP地址
    serv_addr.sin_port = htons(1234);  //端口
    
    bind(serv_sock_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

    //进入监听状态，等待用户发起请求
    listen(serv_sock_fd, 20);
    printf("监听结束\n");
    //接收客户端请求
    struct sockaddr_in clnt_addr;
    socklen_t clnt_addr_size = sizeof(clnt_addr);
    clnt_sock_fd = accept(serv_sock_fd, (struct sockaddr*)&clnt_addr, &clnt_addr_size);
    
    printf("accept end\r\n");
    
    pthread_t tid;    
    pthread_create(&tid, NULL, TCP_send, "TCP_send");
    
    while(1) {
        recv(clnt_sock_fd, read_buff, sizeof(read_buff)-1, 0);
        printf("\033[5D");
        printf("Message form client: %s\r\nself:", read_buff);
        fflush(stdout);
        if (read_buff[0] == 'b' && read_buff[1] == 'y' && read_buff[2] == 'e') {
            printf("exit connect\r\n");
            //send(clnt_sock_fd, "bye!", 5, 0);
            pthread_cancel(tid);
            
            break;
        }
            
        if (g_flag_exit)
            break;
    }

    printf("\n");

    //关闭套接字
    close(clnt_sock_fd);
    close(serv_sock_fd);

    return 0;
}




/*
 *@brief  通过getchar()获取输入的字符串
 *@param  buff:存放输入字符串
 *@return count：输入的字符数
 * */
int getchar_input_str(char * input_buff)
{
    char input_char, count = 0;
    
    /*获取输入字符*/
    while((input_char = getchar()) != '\n'){
        input_buff[count] = input_char;
        count ++;
    }
    /*清除键盘输入缓存*/
    if(input_char != '\n'){
        while(((input_char = getchar()) != '\n') && (input_char != EOF));
    }
    /*字符串结尾以‘\0’结束*/
    input_buff[count] = '\0';
    
    return count;
    
}
